<script setup>
	import { defineEmits, defineExpose, ref } from 'vue'
	import { message } from 'ant-design-vue'
	import { useCustomQueryStore } from '@/views/plugin/dashboard/store/customQuery'
	import SqlEditor from './component/SqlEditor.vue'
	import QueryPreview from './component/QueryPreview.vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'

	const store = useCustomQueryStore()
	const sqlEditor = ref()
	const queryPreview = ref()
	const emit = defineEmits(['onSave'])
	// 监听选中表的变化
	watch(
		() => store.formData.config.selectedTables,
		async (newTables) => {
			if (newTables && newTables.length > 0) {
				// 加载所有选中表的字段信息
				for (const table of newTables) {
					if (!store.formData.config.tableFields[table]) {
						try {
							const res = await dataConnectorApi.metadata({
								id: store.formData.dataConnectorId,
								tableName: table
							})
							store.updateTableFields({
								...store.formData.config.tableFields,
								[table]: res.columns.map((column) => ({
									title: `${column.name}${column.comment ? ` (${column.comment})` : ''}`,
									value: column.name,
									table: table
								}))
							})
						} catch (error) {
							console.log(error)
							message.error(`获取表${table}的字段信息失败`)
						}
					}
				}
				// 更新SQL编辑器的表信息，用于自动补全
				updateEditorTables()
			}
		}
	)

	// 更新编辑器的表信息
	const updateEditorTables = () => {
		if (sqlEditor.value && sqlEditor.value.cminstance) {
			const tables = {}
			Object.entries(store.formData.config.tableFields).forEach(([tableName, fields]) => {
				tables[tableName] = fields.map((f) => f.value)
			})
			sqlEditor.value.cminstance.options.hintOptions.tables = tables
		}
	}

	const onOpen = (record) => {
		if (record) {
			record.config = record.customItemConfig
			store.setFormData(record)
		}
	}

	defineExpose({
		onOpen,
		getConfig: async () => {
			try {
				// 检查SQL语句是否为空
				if (!store.formData.config.sql.trim()) {
					message.error('SQL查询语句不能为空')
					return null
				}

				return {
					...store.formData.config,
					type: 'stat'
				}
			} catch (error) {
				console.error('获取配置失败:', error)
				message.error('获取配置失败：' + (error.message || '未知错误'))
				return null
			}
		}
	})
</script>

<template>
	<div class="w-full">
		<!-- SQL编辑器和预览区域 -->
		<a-row :gutter="16">
			<a-col :span="24">
				<SqlEditor
					v-model:value="store.formData.config.sql"
					v-model:selectedTables="store.formData.config.selectedTables"
					:tableFields="store.formData.config.tableFields"
					:dataConnectorId="store.formData.dataConnectorId"
					@onSave="(val) => emit('onSave', val)"
					ref="sqlEditor"
				/>
			</a-col>
			<a-col :span="24">
				<QueryPreview
					:dataConnectorId="store.formData.dataConnectorId"
					:sql="store.formData.config.sql"
					:params="store.formData.config.params"
					ref="queryPreview"
				/>
			</a-col>
		</a-row>
	</div>
</template>

<style scoped>
	.param-item {
		margin-bottom: 24px;
	}

	.sql-editor {
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		min-height: 200px;
	}

	.sql-editor :deep(.cm-editor) {
		height: 500px;
		font-family: 'Consolas', 'Monaco', monospace;
		font-size: 14px;
	}

	.sql-editor :deep(.cm-gutters) {
		background-color: #f7f7f7;
		border-right: 1px solid #ddd;
	}
</style>
